package lee.study.StackAndQueue;

import java.util.LinkedList;
import java.util.Queue;

public class UseQueueToStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public UseQueueToStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if (Empty()) {//第一次入栈将x放到queue1中
            queue1.add(x);
        } else {
            if (queue1 != null) {
                queue1.add(x);
            } else {
                queue2.add(x);
            }
        }
    }
    public int pop() {
        if (Empty()) {
            return -1;
        }
        int data = 0;
        int qSize1 = queue1.size();
        int qSize2 = queue2.size();
        if (!queue1.isEmpty()) {
            for (int i = 0; i < qSize1 - 1; i++) {
                queue2.offer(queue1.poll());
            }
            data = queue1.poll();
        } else {
            for (int j = 0; j < qSize2 - 1; j++) {
                queue1.offer(queue2.poll());
            }
            data = queue2.poll();
        }
        return data;
    }

    public int top() {
        if (Empty()) {
            return -1;
        }
        int data = 0;
        int qSize1 = queue1.size();
        int qSize2 = queue2.size();
        if (!queue1.isEmpty()) {
            for (int i = 0; i < qSize1; i++) {
                data = queue1.poll();
                queue2.offer(data);
            }
        } else {
            for (int j = 0; j < qSize2; j++) {
                data = queue2.poll();
                queue1.offer(data);
            }
        }
        return data;
    }

    public boolean Empty() {
        if(queue1.isEmpty() && queue2.isEmpty()){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        UseQueueToStack stack=new UseQueueToStack();
        stack.push(1);
        System.out.println(stack);
        stack.pop();
        System.out.println(stack);
        System.out.println(stack.Empty());
    }
}
